#define _CRT_SECURE_NO_WARNINGS  1
//一定要动手，例子不管多么简单，建议至少自己手敲一遍看看是否理解了里头的细枝末节。
//一定要学会思考，思考为什么要这样，而不是那样。还要举一反三地思考
#include"Seqlist.h"
void SLInint(SL* ps)
{
	assert(ps);
	ps->a = (SLDataType*)malloc(sizeof(SLDataType)*4);
	if (ps->a == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ps->size = 0;
	ps->capacity = 4;
}
//销毁
void SLDestory(SL* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}
//检查容量
void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		//扩容
		SLDataType* tem = (SLDataType*)realloc(ps->a, ps->capacity * 2 * sizeof(sizeof(SLDataType)));
		if (tem == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->a = tem;
		ps->capacity *= 2;
	}
}
//查找x元素
int SLFind(SL* ps, SLDataType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}

//尾插
void SLPushBack(SL* ps, SLDataType x)
{
	assert(ps);
	/*assert(ps);
	SLCheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;*/
	SLInsert(ps, ps->size, x);
}
//尾删
void SLPopBack(SL* ps)
{
	assert(ps);
	//assert(ps->size>0);
	///*if (ps->size == 0)
	//	return 0;*/
	////ps->a[ps->size - 1] = 0;
	//ps->size -= 1;
	SLErase(ps, ps->size-1);

}
//头插
void SLPushFront(SL* ps, SLDataType x)
{
	assert(ps);
	//SLCheckCapacity(ps);
	////挪动数据（从后向前挪）
	//int  end = ps->size - 1;
	//while (end >= 0)
	//{
	//	ps->a[end+1] = ps->a[end];
	//	end--;
	//}
	//ps->a[0] = x;
	//ps->size++;
	SLInsert(ps, 0, x);
}
//头删
//void SLPopFront(SL* ps)
//{
//	int i = 1;
//	int count = ps->size - 1;
//	while (count--)
//	{
//		ps->a[i - 1] = ps->a[i];
//		i++;
//	}
//	ps->size--;
//}
// 头删
void SLPopFront(SL* ps)
{
	assert(ps);
	//assert(ps->size > 0);
	//int begin = 1;
	//while ((begin < ps->size))
	//{
	//	ps->a[begin - 1] = ps->a[begin];
	//	++begin;
	//}
	//ps->size--;
	SLErase(ps, 0);

}

//在pos位置上插入x
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	//检查pos是否合法
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	int i = 0;
	int end = ps->size - 1;
	int sum = ps->size - pos-1;
	while (sum>=0)
	{
		ps->a[end+1] = ps->a[end];
		end--;
		sum--;
	}
	ps->a[pos] = x;
	ps->size++;
}
//删除pos位置上的值
void SLErase(SL* ps, int pos)
{
	assert(ps);
	//检查pos是否合法
	assert(pos >= 0 && pos < ps->size);
	int i = 0;
	int count = ps->size - pos - 1;
	while (count--)
	{
		ps->a[pos + i] = ps->a[pos + i + 1];
		i++;
	}
	ps->size--;
}

//打印数据
void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
//修改
void SLModify(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	ps->a[pos] = x;
}
